<template>
  <div class="biz-container">
    <table-layout :haveSider="false">
      <template #searchBox>
        <div v-if="isRender">
          <search-layout
            v-if="isRender"
            :formInfos="q_formInfos"
            :formDatas="q_formDatas"
            message=""
            @onFind="onFind"
            @onChangeType="onChangeType"
          ></search-layout>
        </div>
      </template>
      <template #batchOperat>
        <batch-operat-btn 
          :addData="false" @onAddData="onAddData"
          :delectData="false" @onDelectData="onDelectData"
          :optData="optText" @onOptData="onBatchAudit"
        >
          <template #cusBtn>
            <a-button type="primary" icon="reconciliation" @click="onBatchInvoice"> 开票 </a-button>
          </template>
        </batch-operat-btn>
      </template>
      <template #tableList="slotData">
        <a-list-table
            :columns="columns"
            :tableData="listdata"
            :pagination="pagination"
            :isSelecttion="true"
            :loading="loading"
            :scroll="{y:slotData.tableHeight}"
            :changeLayout="changeLayout"
            :renderStateByField="['deliveryState']"
            @onTableChange="handleTableChange"
            @onselectChange="onselectChange"
            @onAction="onAction"
            :links="['deliveryOrderNo']"
            @onTouchlinkCell="onTouchlinkCell"
          >
          </a-list-table>
      </template>
    </table-layout>
     <toDeliveryModal ref="modal" @ok="handleModalSaveOk" @close="handleModalCancel" />
     <editOrderModal ref="editOrderModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
     <viewSaleOrderModal ref="viewSaleOrderModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import tableLayout from '@/views/app/biz/common/index'
import aListInfo from '@/views/app/biz/common/aListInfo'
import aListTable from '@/views/app/biz/common/aListTable'
import toDeliveryModal from './toDeliveryModal'
import editOrderModal from './editOrderModal'
import deliveryDetail from './deliveryDetail'
import viewSaleOrderModal from '../saleOrder/viewModal.vue'
import {
  receiveOrder,
  sendOrder,
  getByConditions,
  getByConditionsCount,
} from './saleDelivery'
import { appState } from '@/store/stateTable'
import {columns,q_formInfos,q_formDatas} from './dataConfig'

export default {
  components: {
    searchLayout,
    batchOperatBtn,
    tableLayout,
    aListInfo,
    aListTable,
    editOrderModal, 
    toDeliveryModal,
    viewSaleOrderModal,
    deliveryDetail
  },
  data() {
    return {
      isRender:true,
      columns: columns,
      listdata: [],
      loading: false,
      detailPid:'nodata',
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 1000, //每页显示条数 pageSize
        total: 1,
        // showQuickJumper: true,
        // showSizeChanger: true,
        // pageSizeOptions: ['2', '10', '50', '100'],
      },
      // 查询表单
      q_formInfos: q_formInfos,
      // 查询表单绑定数据
      q_formDatas: q_formDatas,
      pData: {}, // 条件查询参数
      isJump:false,
      optText: '',//发货
      selectedRowKeys: [],
      selectedRows: [],
      notAudit: false,
      changeLayout:false
    }
  },
  computed: {},
  watch: {
      $route: {
          handler: function (val, oldVal) {
            console.log(this.$route.name); 
            console.log(this.$route.meta);  
            //判断是进入该页面还是离开 
            if (this.$route.name=='settlementByDelivery') {
              //读取该页面是否缓存，未缓存时：
              if (!this.$route.meta.keepAlive) {
                //读取页面初始状态
                this.q_formDatas.deliveryState=this.$route.meta.zhuangTai?this.$route.meta.zhuangTai:'已收货'
                //读取页面跳转传参
                if(this.$route.params.keHuPid){
                  this.q_formDatas.keHuPid=this.$route.params.keHuPid
                }
                this.getTotal()
                this.getList(this.q_formDatas)
              }else{
                console.log(this.$route.params.isBack);
                //已缓存时判断是否是返回
                if (!this.$route.params.isBack) {
                  this.getTotal()
                  this.getList(this.q_formDatas)
                }
                this.isJump=false
              }
            }
          },
          deep: true,
          immediate:true
      }
    },
  beforeRouteLeave(to,from,next){
    if (this.isJump) {
      from.meta.keepAlive=true
    }else{
      from.meta.keepAlive=false
    }
    next();
  },
  mounted(){
    
  },
  methods: {
    formatParms(){
      let sbdata=JSON.parse(JSON.stringify(this.q_formDatas))
      for (let key in sbdata) {
        // console.log(key,sbdata[key]);
        if (!sbdata[key]){
          sbdata[key]=null  
        }
        if (key=='deliveryOrderNo') {
          if (sbdata[key]==null) {
            sbdata[key]=`%%`
          }else{
            sbdata[key]=`%${sbdata[key]}%`
          }
          
        }
      }
      return sbdata
    },
    // 初始化页面时得到总数
    async getTotal() {
      let pages = ''
      pages = await getByConditionsCount(this.formatParms())
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        this.pagination.showTotal =  (showTotal) => {return `共 ${showTotal} 条`}
      }
    },
    // 初始化查询时的数据列表
    async getList(params) {
      console.log('请求列表时传入的数据', this.formatParms())
      let actionBtn=[]
      this.loading = true
      let listdata = []
      let res = ''
      res = await getByConditions(this.formatParms(), this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
        let haveId=resdata.find(item=>{return item.pid==this.detailPid})
        if (!haveId) {
          this.detailPid='nodata'
        }
        for (let item of resdata) {
          // switch (item.deliveryState) {
          //   case '已收货':
          //     actionBtn = ['发票']
          //     break
          // }
          listdata.push({
            key: item.pid,
            action:actionBtn,
            ...item
            })
        }
         this.listdata =listdata
      } else {
        this.listdata = []
      }
      console.log(this.listdata)
    },
    // 新增按钮 点击了新增
    onAddData() {
      this.$refs.modal.addModal()
    },
    // 关闭模态详细框
    handleModalCancel() {
    },
    // 模态详细框提交按钮
    handleModalSaveOk() {
      this.getList(this.q_formDatas)
    },
    // 操作按钮
    onAction(text, record, index) {
      
    },

    // 触发改变页码,筛选,排序时的回调
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    // 查询按钮
    onFind (){
      this.pagination.current = 1
      this.getTotal()
      this.getList(this.q_formDatas)
    },

    onTouchlinkCell( text, record, index,link){
      console.log(record);
      if(link=='deliveryOrderNo'){
        // this.$refs.editOrderModal.editModal(record.pid,record)
        this.$router.push({
          name: 'mergeDetail',
          params: {
            isJump:false,
            pathName:this.$route.name,
            pid:record.pid 
          } 
        })
      }
    },

    // 多选批量操作
    onselectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      for (const item of this.selectedRows) {
        if (item.deliveryState == '待收货') {
          this.notAudit = true
          return
        } else {
          this.notAudit = false
        }
      }
    },
    onDelectData(){
      if(this.selectedRows.length){
        // this.showDelConfirm(this.selectedRows)
      }else{
        this.$message.warning({ content:'未选择要作废的配送单', duration: 3 })
      }
    },
    showRevoke(val,type) {
      let datas=[]
      if(type=='1'){
        datas[0]=val
      }else{
        datas=val
      }
      const that = this;
      this.$confirm({
        title: '是否确认作废？',
        content: '作废后未配送的数量将恢复到订单中！',
        onOk() {
          let reqArr=[]
          let key='self'
          for (const item of datas) {
            reqArr.push(that.revokeOrder(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1' && item.data) {
                that.$message.success({ content:'配送单'+item.data.deliveryOrderNo+ '作废成功', duration: 3 })
              } else {
                that.$message.error({ content:'配送单'+item.data.deliveryOrderNo+ '作废失败，原因：'+item.message, duration: 3 })
              }
            }
            that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content:'操作出错:'+err, duration: 3 })
          })
        },
        onCancel() {},
      });
    },
    async revokeOrder(val){
      console.log(val);
      let sbdata={
        ...val,
        deliveryState:this.appState.deliveryState.revoked.code
      }
      let res = await receiveOrder(sbdata)
      return res
    },
    //发货弹框
    showConfirm(val,type) {
      let datas=[]
      if(type=='1'){
        datas[0]=val
      }else{
        datas=val
      }
      const that = this;
      this.$confirm({
        title: '是否确认发货？',
        content: '发货后请提醒客户查看',
        onOk() {
          let reqArr=[]
          let key='self'
          for (const item of datas) {
            item.deliveryState='待收货'
            reqArr.push(that.pushInfos(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1') {
                that.$message.success({ content:'已发货', duration: 3 })
              } else {
                that.$message.error({ content:'发货失败，原因：'+item.message, duration: 3 })
              }
            }
            that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content:'操作出错:'+err, duration: 3 })
          })
        },
        onCancel() {},
      });
    },
    async pushInfos(val){
      let res = await sendOrder(val)
      return res
    },
    onBatchAudit() {
      if (this.selectedRows.length) {
        if (this.notAudit) {
          this.$message.warning({ content: '已选项中含有已发货的记录，请选择未发货的记录', duration: 3 })
        } else {
          this.showConfirm(this.selectedRows)
        }
      } else {
        this.$message.warning({ content: '未选择要发货的记录', duration: 3 })
      }
    },
    onBatchInvoice() {
      if (this.selectedRows.length) {
        this.$router.push({
          name: 'toInvoicing',
          params: {
            isJump:false,
            pathName:this.$route.name,
            pid:null,
            orderType:'delivery',
            order:this.selectedRows,
            type:'add'
          } 
        })
      } else {
        this.$message.warning({ content: '未选择要开票的记录', duration: 3 })
      }
    },
    // 搜索栏选择下拉select触发搜索val[0]表示选中的record中的pid,val[1]表示选中的record全部信息
    onChangeType(name, val) {
      console.log('formName',name)
      console.log('val',val)
      switch (name) {
        case 'deliveryType': 
          if (!val) {
            this.q_formDatas.deliveryType=null
          }else{
            this.q_formDatas.deliveryType=val
          }
          this.onFind ()
          break 
        case 'deliveryOrderNo':
          if (!val) {
            this.q_formDatas.deliveryOrderNo=null
          }
          this.onFind ()
          break
        case 'customerPid':
          if (!val) {
            this.q_formDatas.customerPid=null
          }
          this.onFind ()
          break
      }
    },
  },
}
</script>

<style>
</style>